<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { roleApi, permissionApi } from '../../api'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 1,
  permissionIds: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 权限选项
const permissionOptions = ref([])

// 获取权限列表
const fetchPermissionOptions = async () => {
  try {
    const res = await permissionApi.getAllPermissions()
    console.log('获取权限列表响应:', res)
    
    // 检查响应数据结构
    let permissions = []
    if (res && Array.isArray(res)) {
      permissions = res
    } else if (res && res.list && Array.isArray(res.list)) {
      // 如果返回的是包含list的对象
      permissions = res.list
    } else if (res && res.data && Array.isArray(res.data)) {
      // 如果返回的是包含data的对象
      permissions = res.data
    } else {
      console.error('未知的权限列表数据结构:', res)
      permissions = []
    }
    
    permissionOptions.value = permissions.map(permission => ({
      id: permission.id,
      name: permission.name
    }))
  } catch (error) {
    console.error('获取权限列表失败:', error)
  }
}

// 表单引用
const formRef = ref()

// 初始化数据
onMounted(() => {
  fetchData()
  fetchPermissionOptions()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: searchForm.name,
      code: searchForm.code,
      status: searchForm.status
    }
    const res = await roleApi.getRoleList(params)
    console.log('获取角色列表响应:', res)
    
    // 检查响应数据结构
    if (res.records && Array.isArray(res.records)) {
      tableData.value = res.records
      pagination.total = res.total || 0
    } else if (res.list && Array.isArray(res.list)) {
      // 如果返回的是包含list的对象
      tableData.value = res.list
      pagination.total = res.total || 0
    } else if (Array.isArray(res)) {
      // 如果返回的是数组
      tableData.value = res
      pagination.total = res.length
    } else {
      console.error('未知的角色列表数据结构:', res)
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加角色'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = async (row: any) => {
  console.log('编辑角色数据:', row)
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.description = row.description
  form.status = row.status
  
  // 处理权限ID列表
  if (row.permissionIds && Array.isArray(row.permissionIds)) {
    form.permissionIds = row.permissionIds
    console.log('设置权限ID列表:', row.permissionIds)
  } else if (row.permissions && Array.isArray(row.permissions)) {
    // 如果返回的是权限对象数组，尝试提取ID
    form.permissionIds = row.permissions.map(p => p.id).filter(id => id !== undefined)
    console.log('从权限对象提取ID列表:', form.permissionIds)
  } else {
    form.permissionIds = []
    console.log('未找到权限信息，设置为空数组')
  }
}

// 删除角色
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该角色吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await roleApi.deleteRole(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑角色
          await roleApi.updateRole({
            id: form.id,
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status,
            permissionIds: form.permissionIds
          })
          ElMessage.success('编辑成功')
        } else {
          // 添加角色
          await roleApi.addRole({
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status,
            permissionIds: form.permissionIds
          })
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error(isEdit.value ? '编辑角色失败:' : '添加角色失败:', error)
        ElMessage.error(isEdit.value ? '编辑角色失败' : '添加角色失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.name = ''
  form.code = ''
  form.description = ''
  form.status = 1
  form.permissionIds = []
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '启用' : '禁用'
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}
</script>

<template>
  <div class="role-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加角色</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="120" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="permissions" label="权限" min-width="200">
          <template #default="{ row }">
            <el-tag v-for="(permission, index) in row.permissions" :key="index" size="small" style="margin-right: 5px; margin-bottom: 5px;">
              {{ permission }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限">
          <el-checkbox-group v-model="form.permissionIds">
            <el-checkbox
              v-for="item in permissionOptions"
              :key="item.id"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>